package com.yaorange.module.filter;

import com.yaorange.response.Result;
import com.yaorange.utils.JwtUtil;
import com.yaorange.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 设置CORS响应头
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        String method = request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }


        String url = request.getRequestURL().toString();
        if (url.contains("/user/login")){
            // 用户正在登录，则放行
            filterChain.doFilter(request, response);
            return;
        }
        // 获取token
        String token = request.getHeader("Token");
        if (token != null) {
            try {
                // 验证token
                Claims claims = jwtUtil.parseToken(token);
                if (claims != null) {
                    // 获取用户编号/是否是管理员
                    Object sysId = claims.get("id");
                    Object isAdmin = claims.get("admin");
                    // 组合数据
                    ThreadLocalUtil.set(sysId + "-" + isAdmin);
                    // 在线程中共享数据
                    filterChain.doFilter(request, response);
                    // 清空数据
                    ThreadLocalUtil.remove();
                    return;
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        // 验证失败
        Result<Object> fail = Result.fail(401, "登录已过期|未登录,,请重新登录");
        response.setContentType("application/json;charset=UTF-8");
        Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder = new Jackson2ObjectMapperBuilder();
        // 将对象转换为字符串
        String json = jackson2ObjectMapperBuilder.build().writeValueAsString(fail);
        response.getWriter().write(json);
        response.getWriter().flush();
        //response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
}
